package org.lionzhou.chatGG.web.util.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.lionzhou.chatGG.web.config.GGConfig;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;


/**
 * @Description
 * @Author ZhouLiangCheng
 * @Date 2023/1/14
 * @Version 1.0
 */
@Component
@Slf4j
@AllArgsConstructor
public class DingDingUtils {
    ObjectMapper objectMapper;

    GGConfig ggConfig;

    public void blindBoxSendMsg(String msg) {
        DingMsg dingMsg = new DingMsg();
        dingMsg.setMsgtype("text");
        DingMsgContent dingMsgContent = new DingMsgContent();
        dingMsg.setText(dingMsgContent);
        dingMsgContent.setContent(String.format("GG:%s", msg));

        try {
            String body = objectMapper.writeValueAsString(dingMsg);
            log.info("body:{}", body);
            HttpRequest httpRequest = HttpRequest.newBuilder()
                    .timeout(Duration.ofSeconds(900))
                    .uri(URI.create(ggConfig.getDingDingHook()))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(body))
                    .build();
            HttpResponse.BodyHandler<byte[]> bodyHandler = HttpResponse.BodyHandlers.ofByteArray();
            CompletableFuture<HttpResponse<byte[]>> future = HttpClient.newHttpClient().sendAsync(httpRequest, bodyHandler);

            future.thenApply(HttpResponse::body)
                    .thenAccept((r) -> {
                        log.info(new String(r));
                    })
                    .join();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Data
    public static class DingMsg {
        String msgtype;
        DingMsgContent text;
    }

    @Data
    public static class DingMsgContent {
        String content;
    }
}
